import { Button, message, Space, TypographyText } from 'ant-design-vue'
import moment from 'moment'
import { defineComponent, nextTick, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { omit } from 'xe-utils'

import { marketingApi } from '@/apis'
import { CommodityItem } from '@/apis/marketingTypes'
import { type ProTableProps, type ProTableRef, ProTable } from '@/components'
import { TABLE_FORMAT, TABLE_ITEM_RENDER, TABLE_RENDERER } from '@/constants'
import { useDialog } from '@/hooks'
import { bus, isValueEmpty } from '@/utils'
import { handlePricePoint } from '@/utils/bsshow'

import NewsUpMsgDialog from '../components/newsUpMsgDialog'

export default defineComponent({
  name: 'ExchangeCommodity',
  setup() {
    const newsDlgRef = ref(null)
    const statusOptions = [
      { label: '下架', value: 0 },
      { label: '上架', value: 1 }
    ]

    const tableRef = ref({} as ProTableRef)
    const tableConfig = ref({
      fixedHeight: true,
      options: {
        border: true,
        align: 'center',
        toolbarConfig: {
          slots: {
            buttons: 'toolbarButtons'
          }
        },
        formConfig: {
          items: [
            {
              title: '开始时间',
              field: 'startTime',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['startBeginTime', 'startEndTime']
                }
              }
            },
            {
              title: '结束时间',
              field: 'endTime',
              itemRender: {
                name: TABLE_RENDERER.FormItemDate,
                props: {
                  type: 'range',
                  placeholder: ['开始时间', '结束时间'],
                  valueFormat: 'x',
                  showTime: {
                    defaultValue: [
                      moment('00:00:00', 'HH:mm:ss'),
                      moment('23:59:59', 'HH:mm:ss')
                    ]
                  },
                  keys: ['endBeginTime', 'endEndTime']
                }
              }
            },
            {
              title: '上新商品',
              field: 'newGoods',
              itemRender: {
                name: TABLE_ITEM_RENDER.ACheckbox,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: [{ label: ' ', value: 1 }]
              }
            },
            {
              title: '商品状态',
              field: 'status',
              itemRender: {
                name: TABLE_ITEM_RENDER.ASelect,
                props: {
                  placeholder: '全部',
                  allowClear: true
                },
                options: statusOptions
              }
            },

            {
              title: '关键词',
              field: 'keyword',
              itemRender: {
                name: TABLE_ITEM_RENDER.AInput,
                props: {
                  placeholder: '商品名称或商品编码',
                  allowClear: true
                }
              }
            },
            {
              itemRender: {
                name: TABLE_RENDERER.FormItemBtns
              }
            }
          ]
        },
        columnConfig: {
          minWidth: 100
        },
        columns: [
          {
            type: 'checkbox',
            width: 50
          },
          {
            title: 'ID',
            field: 'id',
            width: 80
          },
          {
            title: '商品名称',
            field: 'goodsName',
            minWidth: 150
          },
          {
            title: '商品编码',
            field: 'goodsCode',
            minWidth: 120
          },
          {
            title: '活动库存',
            field: 'exchangeStock'
          },
          {
            title: '兑换价格',
            width: 120,
            slots: {
              default: 'salePrice'
            }
          },
          {
            title: '已兑数量',
            field: 'exchangedStock'
          },
          {
            title: '可兑会员',
            slots: {
              default: 'validMember'
            }
          },
          {
            title: '兑换开始时间',
            field: 'exchangeStartTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 150
          },
          {
            title: '兑换结束时间',
            field: 'exchangeEndTime',
            formatter: [TABLE_FORMAT.Date, 'yyyy-MM-dd HH:mm:ss'],
            minWidth: 150
          },
          {
            title: '状态',
            fixed: 'right',
            slots: {
              default: 'status'
            },
            width: 100
          },
          {
            title: '操作',
            slots: {
              default: 'operation'
            },
            width: 120,
            fixed: 'right'
          }
        ],
        pagerConfig: {
          pageSize: 15
        },
        proxyConfig: {
          seq: true,
          form: true,
          props: {
            result: 'dataList',
            total: 'page.totalCount'
          },
          ajax: {
            query: async ({ page, form }) => {
              let newGoodsType
              if (!isValueEmpty(form.newGoods)) {
                newGoodsType = 1
              }
              form = omit(form, ['startTime', 'endTime', 'newGoods'])
              const data = await marketingApi.getExchangeCommodityList({
                pageParameter: {
                  pageSize: page.pageSize,
                  currentPage: page.currentPage
                },
                newGoodsType,
                ...form
              })
              return data
            }
          }
        }
      }
    } as ProTableProps)

    const router = useRouter()
    const { showConfirm } = useDialog()

    function handleAdd() {
      router.push({
        name: 'CommodityCreate'
      })
    }

    function handleEdit(item: CommodityItem) {
      router.push({
        name: 'CommodityEdit',
        query: {
          id: item.id
        }
      })
    }

    //上新推送
    function handleNewsGoodsUp() {
      //@ts-ignore
      newsDlgRef.value.show()
    }

    function handleToggleStatus(item: CommodityItem) {
      const isUp = item.status === 0

      showConfirm({
        content: '确认' + (isUp ? '上架' : '下架') + '商品？',
        onOk: () => {
          tableRef.value.refresh(async () => {
            isUp
              ? await marketingApi.upCommodity(item.id)
              : await marketingApi.downCommodity(item.id)
          })
        }
      })
    }

    function handleViewDetail(item: CommodityItem) {
      router.push({
        name: 'CommodityDetail',
        query: {
          id: item.id
        }
      })
    }

    function handleBatchDelete() {
      const selected = tableRef.value.table.getCheckboxRecords().map(v => v.id)

      if (selected.length === 0) {
        return message.warn('请选择至少1条记录')
      }

      showConfirm({
        content: '确认批量删除？',
        onOk: () => {
          tableRef.value.refresh(async () => {
            await marketingApi.deleteExchangeCommodityList(selected)
          })
        }
      })
    }
    function formatMemberText(star) {
      switch (Number(star)) {
        case 0:
          return '注册粉丝及以上'
        case 1:
          return '推广者及以上'
        case 2:
          return '黑优推广者及以上'
        case 4:
          return '好物推荐官'
        default:
          return ''
      }
    }

    onMounted(() => {
      bus.on('refreshExchangeCommodity', () => {
        nextTick(() => {
          tableRef.value.refresh()
        })
      })
    })

    return {
      tableRef,
      newsDlgRef,
      tableConfig,
      handleAdd,
      handleEdit,
      handleToggleStatus,
      handleViewDetail,
      handleBatchDelete,
      handleNewsGoodsUp,
      formatMemberText
    }
  },
  render() {
    /** 状态机 */
    const statusStateMap = {
      0: '上架',
      1: '下架'
    }

    return (
      <div>
        <ProTable
          ref="tableRef"
          v-slots={{
            toolbarButtons: () => (
              <Space>
                <Button type="primary" onClick={this.handleAdd}>
                  添加兑换商品
                </Button>
                <Button type="primary" onClick={this.handleBatchDelete}>
                  批量删除
                </Button>
                <Button type="primary" onClick={this.handleNewsGoodsUp}>
                  上新推送
                </Button>
              </Space>
            ),
            salePrice: ({ row }) => {
              return (
                <Space>{handlePricePoint(row.exchangePrice, row.point)}</Space>
              )
            },
            validMember: ({ row }) => {
              return <Space>{this.formatMemberText(row.goodsUserStar)}</Space>
            },
            status: ({ row }) => {
              return (
                <Space>
                  {row.status == 0 ? (
                    <TypographyText type="danger">下架</TypographyText>
                  ) : (
                    <TypographyText type="success">上架</TypographyText>
                  )}
                </Space>
              )
            },
            operation: ({ row }) => (
              <Space>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleEdit(row)}
                  disabled={row.status === 1}
                >
                  编辑
                </Button>
                <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleToggleStatus(row)}
                >
                  {statusStateMap[row.status]}
                </Button>
                {/* <Button
                  type="link"
                  size="small"
                  onClick={() => this.handleViewDetail(row)}
                  disabled={row.status === 1 || row.source === 1}
                >
                  商品详情
                </Button> */}
              </Space>
            )
          }}
          {...this.tableConfig}
        />
        <NewsUpMsgDialog ref="newsDlgRef"></NewsUpMsgDialog>
      </div>
    )
  }
})
